import {login, loginAuth, getUserInfo, getUserRoles} from '@/api/global/index'
import {getLocalStorage, xor} from '@/utils/filters'
import Cookie from 'js-cookie'
import axios from 'axios'

const state = {
    // token
    token: Cookie.get('token'),
    // 用户姓名
    realName: getLocalStorage('userInfo', 'realName'),
    // 权限列表
    roles: [],
    // 重新渲染菜单
    reRender: 0,
    // 是否显示全局筛选框
    showSearch: true,
    // 是否是数据管理病案包，筛选框不同
    isDataPackage: false
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_RERENDER: (state) => {
        state.reRender++
    },
    SET_SHOWSEARCH: (state, val) => {
        state.showSearch = val
    },
    SET_ISDATAPACKAGE: (state, val) => {
        state.isDataPackage = val
    }
}
const actions = {
    // 用户登录（ 该方法名字在映射的时候会被改写 user/login => login ）
    login ({dispatch}, userInfo) {
        const {username, password} = userInfo
        return new Promise((resolve, reject) => {
            let params = {
                userName: username,
                password: password
            }
            login(params).then(res => {
                if (res.code.toString() === '200') {
                    Cookie.set('token', res.data, {expires: 1})
                    axios.defaults.headers['Authorization'] = 'Bearer ' + res.data
                    Promise.all([dispatch('getLoginUserInfo'), dispatch('getLoginUserRoles')]).then(response => {
                        resolve(response) // 不需要返回到登录接口，用户数据已处理
                    })
                } else {
                    resolve(res)
                }
            })
                .catch(err => {
                    reject(err)
                })
        })
    },

    // 用户授权登录接口
    loginAuth ({dispatch}, otherInfo) {
        const usrpwd = xor(otherInfo)
        return new Promise((resolve, reject) => {
            let params = {
                usr: '',
                pwd: ''
            }
            // if (usrpwd) {
            params.usr = usrpwd.split('@')[0]
            params.pwd = usrpwd.split('@')[1]
            loginAuth(params).then(res => {
                localStorage.setItem('authToken', res)
                resolve(res)
            })
                .catch(err => {
                    reject(err)
                })
        })
    },

    // 重新获取用户信息
    getUserInfoAgain ({dispatch}) {
        return new Promise((resolve, reject) => {
            Promise.all([dispatch('getLoginUserInfo'), dispatch('getLoginUserRoles')]).then(res => {
                resolve(res)
            })
        })
    },

    // 获取用户信息
    getLoginUserInfo ({commit}) {
        return new Promise((resolve, reject) => {
            getUserInfo().then(res => {
                if (res.code.toString() === '200') {
                    let userInfo = {
                        realName: res.data.userName,
                        mechanism: res.data.userPowerOrgan,
                        checkAuth: res.data.userAccess
                    }
                    localStorage.setItem('userInfo', JSON.stringify(userInfo))
                    localStorage.setItem('userMechanism', JSON.stringify(res.data.userOrgan))
                    localStorage.setItem('userType', JSON.stringify(res.data.userRole.roleType))
                    let orgId = getLocalStorage('globalSearch', 'orgId')
                    // 查询详情时间限制
                    let index = res.data.userPowerOrgan.findIndex(item => item.id === orgId)
                    if (index !== -1) {
                        localStorage.setItem('viewDeadlineDays', res.data.userPowerOrgan[index].viewDeadlineDays)
                    }
                    // 科室重置或选中
                    let flagOrg = res.data.userPowerOrgan.filter(item => item.id === orgId)
                    let depId = getLocalStorage('globalSearch', 'departmentId')
                    let flagDep = JSON.stringify(res.data.userPowerOrgan).indexOf(depId) === -1
                    if (!flagOrg.length) {
                        localStorage.setItem('globalSearch', JSON.stringify({
                            ...getLocalStorage('globalSearch'),
                            orgId: '',
                            departmentId: '',
                            cykb: '',
                            cybf: '',
                            bmy: ''
                        }))
                    } else if (flagDep) {
                        localStorage.setItem('globalSearch', JSON.stringify({
                            ...getLocalStorage('globalSearch'),
                            departmentId: '',
                            cykb: '',
                            cybf: ''
                        }))
                    }
                    resolve(res)
                } else {
                    resolve(res)
                }
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 获取用户拥有权限
    getLoginUserRoles ({commit}) {
        return new Promise((resolve, reject) => {
            getUserRoles().then(res => {
                if (res.code.toString() === '200') {
                    let arr = []
                    res.data.forEach(item => {
                        arr.push(parseInt(item.id))
                    })
                    arr.push(999999999999)
                    localStorage.setItem('rolesCode', JSON.stringify(arr))
                    resolve(res)
                } else {
                    resolve(res)
                }
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 退出登录
    logout ({commit}) {
        return new Promise((resolve, reject) => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            localStorage.removeItem('globalSearchDRG')
            localStorage.removeItem('globalFormDRG')
            localStorage.removeItem('globalSearchQC')
            localStorage.removeItem('globalFormQC')
            localStorage.removeItem('userInfo')
            localStorage.removeItem('userMechanism')
            localStorage.removeItem('userType')
            localStorage.removeItem('viewDeadlineDays')
            localStorage.removeItem('globalSearch')
            localStorage.removeItem('globalSearchQC')
            localStorage.removeItem('rolesCode')
            localStorage.removeItem('tagsView')
            localStorage.removeItem('tagsViewQC')
            localStorage.removeItem('tagsViewMS')
            localStorage.removeItem('searchForm')
            localStorage.removeItem('searchFormQC')
            localStorage.removeItem('searchFormMS')
            localStorage.removeItem('listQuery')
            localStorage.removeItem('cloudMode')
            Cookie.remove('sidebarStatus_drg')
            Cookie.remove('sidebarStatus')
            Cookie.remove('size')
            Cookie.remove('timeLeft')
            Cookie.remove('initlogout')
            Cookie.remove('token')
            Cookie.remove('isPackage')
            Cookie.set('optOut', 'optOut')
            sessionStorage.clear()
            resolve()
        })
    },
    // 重新渲染组件
    updateReRender ({commit}) {
        commit('SET_RERENDER')
    },
    // 是否显示全局筛选框
    isShowSearch ({commit}, val) {
        commit('SET_SHOWSEARCH', val)
    },
    // 数据管理病案包筛选框
    showPackage ({commit}, val) {
        Cookie.set('isPackage', val)
        commit('SET_ISDATAPACKAGE', val)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
